package cn.jhc.db;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import cn.jhc.bean.Article;

public class ArticleDao {
	
	private static final String CREATESQL = "insert into article(content, publish, owner) values(?, ?, ?)";
	private static final String FINDBYUSERSQL = "select id, content, publish, owner "
			+ "from article where owner=? "
			+ "order by publish desc limit ?,5";
	
	private QueryRunner runner;

	public ArticleDao(QueryRunner runner) {
		this.runner = runner;
	}

	public void create(Article article) throws IOException{
		try {
		runner.execute(CREATESQL, article.getContent(), article.getPublish(), article.getOwner());
		} catch (SQLException e) {
			e.printStackTrace();
			throw new IOException(e);
		}
	}
	
	public List<Article> findByUser(int owner, int page) throws IOException {
		List<Article> list = null;
		 try {
			list = runner.query(FINDBYUSERSQL, new BeanListHandler<>(Article.class), owner, page * 5);
		} catch (SQLException e) {
			e.printStackTrace();
			throw new IOException(e);
		}
		 return list;
	}
}
